package yrjdezu.abab.engineerpractice2.service.impl;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import yrjdezu.abab.engineerpractice2.service.IFilesService;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class FilesServiceImpl implements IFilesService {

    private final Path fileStorageLocation;

    public FilesServiceImpl() {
        // 实际应用中应从配置读取
        this.fileStorageLocation = Paths.get("uploads").toAbsolutePath().normalize();
    }

    @Override
    public Resource getFileAsResource(String fileId) throws IOException {
        try {
            Path filePath = this.fileStorageLocation.resolve(fileId).normalize();
            Resource resource = new UrlResource(filePath.toUri());

            if(resource.exists()) {
                return resource;
            } else {
                throw new IllegalArgumentException("文件不存在: " + fileId);
            }
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("文件路径无效: " + fileId, e);
        }
    }
}